package com.gemme.gemme.wode;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gemme.gemme.BaseActivity;
import com.gemme.gemme.MainActivity;
import com.gemme.gemme.R;
import com.gemme.gemme.login.Constant;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.manager.DataPares;
import com.gemme.gemme.test.MyPhotoFragment;
import com.gemme.gemme.util.MyOSSUtils;
import com.gemme.gemme.util.SPUtil;
import com.gemme.gemme.view.GMPhotoView;
import com.gemme.gemme.view.Topview;
import com.jaeger.library.StatusBarUtil;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.photoview.PhotoView;
import com.luck.picture.lib.tools.PictureFileUtils;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;

//侧滑删除地址
public class PhotoMyActivity extends BaseActivity{

    private Bundle savedInstanceState;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.savedInstanceState = savedInstanceState;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_phone_my);
        initTop();
        initView();
        getIntentData();
    }
    int type;
    private void getIntentData() {
        Intent intent = getIntent();

        type = intent.getIntExtra("type",-1);
    }

    private void initTop() {
        StatusBarUtil.setTransparent(this);
        findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }
    boolean isFirst = true;
    GMPhotoView photoView;
    TextView tv_fabu;
    TextView close;
    EditText editTitle;
    EditText editContent;
    private void initView() {
//        全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()

        photoView = findViewById(R.id.photoView);
//        photoView.setChooseMode(PictureMimeType.ofImage());
        photoView.setChooseMode(type);
        //首次进入pictureSelect
        photoView.setClickToPicture();

        close = findViewById(R.id.close);
        tv_fabu = findViewById(R.id.tv_fabu);

        editTitle = findViewById(R.id.editTitle);
        editContent = findViewById(R.id.editContent);
        tv_fabu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int intsq_type = type == PictureMimeType.ofImage() ?  1 : 2;
                if (intsq_type == 1){
                    toOssPic();
                }else{
                    toOssVideo();
                }

            }
        });

    }

    private void toOssVideo() {
        try {
//            type == PictureMimeType.ofImage() ?  判断是否为图片上传
            if(data == null || data.size() == 0)
                return;



            long l = System.currentTimeMillis();
//            String videopath = "/storage/emulated/0/Movies/VID_20200716_11564190.mp4";
            String videopath = data.get(0).getRealPath();
            String videoName =  new File(videopath).getName().replace(".",l+".");
            MyOSSUtils.getInstance().upVideo(this, new MyOSSUtils.OssUpCallback() {
                @Override
                public void successImg(String img_url) {
                    System.out.println("");
                }

                @Override
                public void successVideo(String video_url) {
                    System.out.println("");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            toVideoServer(video_url);
                        }
                    });

                }

                @Override
                public void inProgress(long progress, long zong) {
                    System.out.println("");
                }
            }, videoName, videopath);
        }catch (Exception e){

        }
    }



    private List<String> picList;
    private void toOssPic() {
        try {
//            type == PictureMimeType.ofImage() ?  判断是否为图片上传
            if(data == null || data.size() == 0)
                return;

            ArrayList<String> imageNativepath = new ArrayList<>();
            ArrayList<String> imageUrlpath = new ArrayList<>();
            for (int i = 0; i < data.size(); i++) {
                LocalMedia localMedia = data.get(i);
                imageNativepath.add(localMedia.getCompressPath());
            }
            MyOSSUtils.getInstance().upImageMuti(this,imageNativepath, imageUrlpath, new MyOSSUtils.OnOssUploadListener() {
                @Override
                public void onOssUploadListener(List<String> imageList) {
                    picList = imageList;
                    System.out.println("");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            toPicServer();
                        }
                    });
                }
            });
        }catch (Exception e){

        }
    }

    private void toVideoServer(String videoPath) {
        try {

            String label = editTitle.getText() + "";
            String cdescribe = editContent.getText() + "";
            String userId = SPUtil.getDataForString(mContext, Constant.UserId, "");
            int sq_type = 2;
            if(TextUtils.isEmpty(cdescribe)){
                Toast.makeText(mContext, "正文不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            if(TextUtils.isEmpty(videoPath)){
                Toast.makeText(mContext, "视频不能为空", Toast.LENGTH_SHORT).show();
                return;
            }


            if(TextUtils.isEmpty(userId))
                return;

            String url = DataManager.BaseUrl + "community/appccontent/saveComent?" +
                    "userId=" + userId +
                    "&label=" + label +
                    "&type=" + sq_type +
                    "&cDescribe=" + cdescribe +
                    "&videoPath=" + videoPath +

                    "";
            HashMap<String, String> headHashMap = new HashMap<>();
            headHashMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
            DataManager.toServer2(mContext, url, DataManager.POST_TYPE, "", headHashMap, new DataManager.GeResponse(){

                @Override
                public void onResponse(String response) {

                    try {
                        System.out.println("");
//                    int code = (new JSONObject(response)).getInt("code");
                        String msg = (new JSONObject(response)).getString("msg");
                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                        if(DataPares.isSucess(mContext,response)){
                            finish();
                        }

                    }catch (Exception e){

                    }
                }
            });

        }catch (Exception e){

        }

    }

    //发布图片
    private void toPicServer() {
        try {
            String label = editTitle.getText() + "";
            String cdescribe = editContent.getText() + "";
            String userId = SPUtil.getDataForString(mContext, Constant.UserId, "");
            int sq_type = 1;
            if(TextUtils.isEmpty(cdescribe)){
                Toast.makeText(mContext, "正文不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            if(picList == null || picList.size() == 0){
                Toast.makeText(mContext, "图片不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            String picturePath = getPiturePath();

            if(TextUtils.isEmpty(userId))
                return;
            String coverPath = "";
            if(picList != null && picList.size() != 0){
                coverPath = picList.get(0);
            }
            String url = DataManager.BaseUrl + "community/appccontent/saveComent?" +
                    "userId=" + userId +
                    "&label=" + label +
                    "&type=" + sq_type +
                    "&picturePath=" + picturePath +
                    "&cDescribe=" + cdescribe +
                    "&coverPath=" + coverPath +

                    "";
            HashMap<String, String> headHashMap = new HashMap<>();
            headHashMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
            DataManager.toServer2(mContext, url, DataManager.POST_TYPE, "", headHashMap, new DataManager.GeResponse(){

                @Override
                public void onResponse(String response) {

                    try {
                        System.out.println("");
//                    int code = (new JSONObject(response)).getInt("code");
                        String msg = (new JSONObject(response)).getString("data");
                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                        if(DataPares.isSucess(mContext,response)){
                            Intent intent = new Intent(PhotoMyActivity.this, MainActivity.class);
                            intent.putExtra("id",2);
                            startActivity(intent);
                            finish();
                        }

                    }catch (Exception e){

                    }
                }
            });

        }catch (Exception e){

        }
    }

    private String getPiturePath() {
        String str = "";
        try {

            for (int i = 0; i < picList.size(); i++) {
                String s = picList.get(i);
                if(i == picList.size() - 1){
                    str = str + s;
                }else{
                    str = str + s + ",";
                }

            }

        }catch (Exception e){

        }

        return str;
    }


    List<LocalMedia> data;
    @Override
    protected void onResume() {
        super.onResume();
        if(isFirst){
            isFirst = false;
            return;
        }

        data = photoView.getData();
        if(data == null || data.size() == 0)
            finish();
    }


    /**
     * 注意:
     * super.onBackPressed()会自动调用finish()方法,关闭当前Activity.
     */
    @Override
    public void onBackPressed() {
        super.onBackPressed();
//        Toast.makeText(this, "按下了back键   onBackPressed()", Toast.LENGTH_SHORT).show();
        finish();
    }



}